import type { NextPage } from "next";
import { Box } from "@mui/material";
import { useForm } from "react-hook-form";
import { gql, useMutation } from "@apollo/client";

import toast from "react-hot-toast";
import crypto from "crypto";
import Form from "components/User/Form";
import CenterWrap from "components/CenterWrap";
import BorderCard from "components/BorderCard";
import { useRouter } from "next/router";

interface SignUpInput {
  name: string;
  password: string;
}
/* 定义新用户设置突变*/
const NEW_USER_SETTING = gql`
  mutation Mutation($name: String!, $password: String!) {
    newUserSetting(name: $name, password: $password)
  }
`;
const NewUser: NextPage = () => {
  const [newUserSetting, { data }] = useMutation(NEW_USER_SETTING);
  const router = useRouter();
  const setting = {
    title: "设置你的用户名 & 密码",
    btnTitle: "保存",
    onSubmit({ name, password }) {
      /* 注册逻辑 */
      // 密码加密
      password = crypto.createHash("md5").update(password).digest("hex");

      toast
        .promise(
          newUserSetting({
            variables: {
              name,
              password,
            },
          }),
          {
            loading: "正在保存",
            success: ({ data: { newUserSetting } }) => {
              return "保存成功";
            },
            error: "验证失败",
          }
        )
        .then(() => {
          router.push("/");
        });
    },
    options: [
      {
        name: "name",
        label: "用户名",
        setting: {
          required: true,
        },
      },
      {
        name: "password",
        label: "密码",
        type: "password",
        setting: {
          required: true,
        },
      },
    ],
  };
  return (
    <CenterWrap title="用户信息设置">
      <BorderCard>
        <Form
          {...setting}
          sx={{
            width: {
              md: 1 / 2,
              sm: 1 / 3,
              xs: 1,
            },
          }}
        />
      </BorderCard>
    </CenterWrap>
  );
};

export default NewUser;
